package com.mlan.userap;

import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.mlan.userap.activity.BaseActivity;
import com.mlan.userap.model.MsgEvent;
import com.mlan.userap.okhttp.ApiResponse;
import com.mlan.userap.okhttp.JsonCallBack;
import com.mlan.userap.okhttp.JsonCallBackData;
import com.mlan.userap.okhttp.OkHttpHelper;
import com.mlan.userap.okhttp.RequestBuilder;
import com.mlan.userap.okhttp.model.LoginResponse;
import com.mlan.userap.untils.ConfigManager;
import com.mlan.userap.untils.SPUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;

public class LoginActivity extends BaseActivity {

    private EditText etPhone;
    private EditText etPassword;
    private Button btnLogin;
    private Button btnWechatLogin;
    private CheckBox cbAgree;
    private TextView tvAgreement;
    private TextView tvRegister;
    private TextView tvForgetPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 初始化控件
        etPhone = findViewById(R.id.et_phone);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        btnWechatLogin = findViewById(R.id.btn_wechat_login);
        cbAgree = findViewById(R.id.cb_agree);
        tvAgreement = findViewById(R.id.tv_agreement);
        tvRegister = findViewById(R.id.tv_register);
        tvForgetPassword = findViewById(R.id.tv_forget_password);

        etPhone.setText("18011111111");
        etPassword.setText("123456");
        cbAgree.setChecked(true);

        // Settings.Global.putString(getContentResolver(),"mlanWhitePacks","com.tencent.mm;com.taobao.taobao;com.mlan.appinfo;com.mlan.userap;com.kok.ywyl.p1682377075");
        // Settings.Global.putString(getContentResolver(),"mlanWhiteLimit","0");


        // 设置用户协议和隐私协议可点击
        setupAgreementText();

        // 登录按钮点击事件
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!cbAgree.isChecked()) {
                    ShowToast("请先同意用户协议和隐私协议");
                    return;
                }

                String phone = etPhone.getText().toString().trim();
                String password = etPassword.getText().toString().trim();

                if (phone.isEmpty() || password.isEmpty()) {
                    ShowToast("请输入手机号和密码");
                    return;
                }

                new RequestBuilder("/User/LoginWithAccount")
                        .addPara("phone", phone)
                        .addPara("psw", password)
                        .getData(new JsonCallBackData<LoginResponse>() {
                            @Override
                            public void onSuccess(LoginResponse result) {
                                ConfigManager.saveString("user", result.getToken());
                                SPUtils.putString("token", result.getToken());
                                SPUtils.putLong("userId", result.getUserId());
                                AppConfig.token = result.getToken();
                                AppConfig.userId = result.getUserId();
                                ToMain();
                            }

                            @Override
                            public void onError(Exception error) {

                            }
                        });
            }
        });

        // 微信登录按钮点击事件（模拟）
        btnWechatLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ShowToast("微信登录功能开发中...");
                ToMain();
            }


        });

        // 注册点击事件
        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowToast("跳转到注册页面");
                // 实际开发中可跳转到注册页面
            }
        });

        // 忘记密码点击事件
        tvForgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowToast("跳转到忘记密码页面");
                // 实际开发中可跳转到忘记密码页面
            }
        });
    }

    private void ToMain() {
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        finish();
    }

    private void ShowToast(String str) {
        Toast.makeText(LoginActivity.this, str, Toast.LENGTH_SHORT).show();
    }

    // 设置用户协议和隐私协议可点击
    private void setupAgreementText() {
        String text = "我已阅读并同意用户协议和隐私协议";
        SpannableString spannableString = new SpannableString(text);

        // 用户协议可点击
        ClickableSpan userAgreementSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {

                showAgreementDialog("用户协议", "这里是用户协议内容...");
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(0xFF1E88E5); // 蓝色
                ds.setUnderlineText(false);
            }
        };

        // 隐私协议可点击
        ClickableSpan privacyAgreementSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                showAgreementDialog("隐私协议", "这里是隐私协议内容...");
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(0xFF1E88E5); // 蓝色
                ds.setUnderlineText(false);
            }
        };

        spannableString.setSpan(userAgreementSpan, 7, 11, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(privacyAgreementSpan, 12, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvAgreement.setText(spannableString);
        tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void msgEvent(MsgEvent event) {

    }

    // 显示协议弹窗
    private void showAgreementDialog(String title, String content) {
//        new AlertDialog.Builder(LoginActivity.this)
//                .setTitle(title)
//                .setMessage(content)
//                .setPositiveButton("确定", (dialog, which) -> dialog.dismiss())
//                .show();
        ShowToast(title + "-" + content);
    }

    // 调用HTTP登录接口
    private void login(String phone, String password) {
        OkHttpClient client = new OkHttpClient();
        FormBody formBody = new FormBody.Builder()
                .add("phone", phone)
                .add("password", password)
                .build();

        Request request = new Request.Builder()
                .url("http://your-login-api-endpoint") // 替换为实际的登录接口URL
                .post(formBody)
                .build();

        ShowToast("-login");
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(@NonNull Call call, @NonNull IOException e) {
//                runOnUiThread(() ->
//                        Toast.makeText(LoginActivity.this, "登录失败：" + e.getMessage(), Toast.LENGTH_SHORT).show()
//                );
//            }
//
//            @Override
//            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//                final String responseBody = response.body() != null ? response.body().string() : "";
//                runOnUiThread(() -> {
//                    if (response.isSuccessful()) {
//                        Toast.makeText(LoginActivity.this, "登录成功：" + responseBody, Toast.LENGTH_SHORT).show();
//                        // 跳转到主页面
//                    } else {
//                        Toast.makeText(LoginActivity.this, "登录失败：" + responseBody, Toast.LENGTH_SHORT).show();
//                    }
//                });
//            }
//        });
    }
}